package com.sakura.动态规划;

import java.util.Arrays;

public class Code91_解码方法 {

    // 暴力递归
    public int numDecodings1(String s) {
        return f1(s.toCharArray(), 0);
    }

    private int f1(char[] chs, int i) {
        if (i == chs.length) {
            return 1;
        }
        if (chs[i] == '0') {
            return 0;
        }
        int ans = f1(chs, i + 1);
        if (i < chs.length - 1 && ((chs[i] - '0') * 10 + (chs[i + 1] - '0') <= 26)) {
            ans += f1(chs, i + 2);
        }
        return ans;
    }

    // 记忆化搜索
    public int numDecodings2(String s) {
        int[] dp = new int[s.length() + 1];
        Arrays.fill(dp, -1);
        return f2(s.toCharArray(), 0, dp);
    }

    private int f2(char[] chs, int i, int[] dp) {
        if (i == chs.length) {
            return 1;
        }
        if (dp[i] != -1) {
            return dp[i];
        }
        int ans;
        if (chs[i] == '0') {
            ans = 0;
        } else {
            ans = f2(chs, i + 1, dp);
            if (i < chs.length - 1 && ((chs[i] - '0') * 10 + (chs[i + 1] - '0') <= 26)) {
                ans += f1(chs, i + 2);
            }
        }
        dp[i] = ans;
        return ans;
    }

    // 自底向上
    public int numDecodings3(String str) {
        char[] s = str.toCharArray();
        int n = s.length;
        int[] dp = new int[n + 1];
        dp[n] = 1;
        for (int i = n - 1; i >= 0; i--) {
            if (s[i] == '0') dp[i] = 0;
            else {
                dp[i] = dp[i + 1];
                if (i < n - 1 && ((s[i] - '0') * 10 + (s[i + 1] - '0') <= 26)) {
                    dp[i] += dp[i + 2];
                }
            }
        }
        return dp[0];
    }
}
